﻿//*** Guidance generated code ***//

using System;
using System.Linq;
using System.Diagnostics;
using System.Reflection;
using System.Web.Mvc;

using Castle.DynamicProxy;

using ProjectBase.Core;

namespace $safeprojectname$.IoC
{
    public class TracingFilter : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            var isProperty = invocation.Method.Name.StartsWith("get_")
                          || invocation.Method.Name.StartsWith("set_");

            if (isProperty)
            {
                invocation.Proceed();
                return;
            }

            LogMethod(invocation);
        }

        protected virtual void LogMethod(IInvocation invocation)
        {
            var target = (invocation.InvocationTarget ?? invocation.Proxy).GetType().Name;
            var stopwatch = Stopwatch.StartNew();

            PublishingManager.Publish(this, // trace published start
                () => "TRACE: Started target '{0}' Method '{1}' started"
                    .FormatWith(target, invocation.Method.Name)
                    , Severity.Debug);
            try
            {
                stopwatch.Start();
                invocation.Proceed();
            }
            finally
            {
                stopwatch.Stop();
                PublishingManager.Publish(this, // trace elapsed time
                () => "TRACE: {2} ms(elapsed); '{0}' Method '{1}': "
                    .FormatWith(target, invocation.Method.Name, stopwatch.ElapsedMilliseconds)
                    , Severity.Debug);
            }
        }
    }
}